#!/usr/bin/env python
#coding:utf-8

import urllib
import re
#import MySQLdb
import sqlite3

def get_weather(city = '上海'):
    # Request For The Web Page
    params = urllib.urlencode({'city':city})
    webpage = urllib.urlopen('http://weather.news.sohu.com/city_inc.php?%s' % params)
    webdata = webpage.read().replace('\n', '')

    # Match The Useful Information
    pattern = re.compile('<td class=blu01>([^<]*)<br>([^<]*)<br>([^<]*)<br>([^<]*)')
    '''db=MySQLdb.connect(host='localhost',      #连接数据库
                      user='test',
                      passwd='test',
                      db='mytable',
                      charset='gb2312')        #设置字符编码
                      '''

    db = sqlite3.connect('weater.db')
    cursor=db.cursor()

    cursor.execute ("DROP TABLE IF EXISTS message")
    cursor.execute ("""
        CREATE TABLE message
            (
              riqi CHAR(40),
              tianqi CHAR(40),
              wendu CHAR(40),         
              fengli CHAR(40),
              jiangshuilv CHAR(40)
            )
      """)
      
    x = 0
    for weather in pattern.findall(webdata):     
        if x == 0:
            riqi='今天'
        elif x == 1:
            riqi='明天'
        else:
            riqi='后天'
        for i in range(4):
            print weather.strip()
        tianqi=weather[0]
        wendu=weather[1]
        fengli=weather[2]
        jiangshuilv=weather[3]
        sss="INSERT INTO message VALUES('%s','%s','%s','%s','%s')"%(riqi,tianqi,wendu,fengli,jiangshuilv)
        cursor.execute(sss)
        db.commit()
        x += 1
    cursor.close()
    db.close()

if __name__ == "__main__":
    get_weather()
